package com.jzo2o.orders.base.handler;

import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.orders.base.enums.OrderPayStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.dto.OrderSnapshotDTO;
import com.jzo2o.orders.base.model.dto.OrderUpdateStatusDTO;
import com.jzo2o.orders.base.service.IOrdersCommonService;
import com.jzo2o.statemachine.core.StatusChangeEvent;
import com.jzo2o.statemachine.core.StatusChangeHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Mr.M
 * @version 1.0
 * @description 支付成功执行的动作
 * @date 2023/12/19 10:11
 */
@Component("order_payed")//bean的名称规则：状态机名称_事件名称
@Slf4j
public class OrderPayedHandler implements StatusChangeHandler<OrderSnapshotDTO> {

    @Resource
    private IOrdersCommonService ordersCommonService;

    @Override
    public void handler(String bizId, StatusChangeEvent statusChangeEventEnum, OrderSnapshotDTO bizSnapshot) {
        log.info("支付成功事件发布执行此动作....");
        //统一对订单状态进行更新，将订单状态由待支付改为派单中
        OrderUpdateStatusDTO orderUpdateStatusReqDTO = new OrderUpdateStatusDTO();
        orderUpdateStatusReqDTO.setId(bizSnapshot.getId());//订单id
        orderUpdateStatusReqDTO.setOriginStatus(OrderStatusEnum.NO_PAY.getStatus());//原始状态待支付
        orderUpdateStatusReqDTO.setTargetStatus(OrderStatusEnum.DISPATCHING.getStatus());//目标状态为派单中
        orderUpdateStatusReqDTO.setPayStatus(OrderPayStatusEnum.PAY_SUCCESS.getStatus());//支付成功
        orderUpdateStatusReqDTO.setTradingOrderNo(bizSnapshot.getTradingOrderNo());//交易单号
        orderUpdateStatusReqDTO.setTransactionId(bizSnapshot.getThirdOrderId());//第三方支付平台的交易单号
        orderUpdateStatusReqDTO.setPayTime(bizSnapshot.getPayTime());//支付时间
        orderUpdateStatusReqDTO.setTradingChannel(bizSnapshot.getTradingChannel());//支付渠道

        Integer integer = ordersCommonService.updateStatus(orderUpdateStatusReqDTO);
        if(integer<1){
            throw new CommonException("订单"+bizSnapshot.getId()+"支付成功事件执行动作失败");
        }

    }
}
